package com.lineage.server.serverpackets;

import com.lineage.server.model.Instance.L1ItemInstance;
import com.lineage.server.model.Instance.L1PcInstance;
import com.lineage.server.model.Instance.L1PetInstance;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class S_PetList extends ServerBasePacket {
  private byte[] _byte;
  
  public S_PetList(int npcObjId, L1PcInstance pc) {
    this._byte = null;
    buildPacket(npcObjId, pc);
  }
  
  private void buildPacket(int npcObjId, L1PcInstance pc) {
    List<L1ItemInstance> amuletList = new ArrayList<>();
    Iterator<L1ItemInstance> iterator = pc.getInventory().getItems().iterator();
    while (iterator.hasNext()) {
      Object itemObject = iterator.next();
      L1ItemInstance item = (L1ItemInstance)itemObject;
      switch (item.getItem().getItemId()) {
        case 40314:
        case 40316:
          if (isWithdraw(pc, item))
            continue; 
          amuletList.add(item);
      } 
    } 
    if (amuletList.size() != 0) {
      writeC(83);
      writeD(70);
      writeH(amuletList.size());
      Iterator<L1ItemInstance> iterator2 = amuletList.iterator();
      while (iterator2.hasNext()) {
        L1ItemInstance item2 = iterator2.next();
        writeD(item2.getId());
        writeC((int)Math.min(item2.getCount(), 2000000000L));
      } 
    } 
  }
  
  private boolean isWithdraw(L1PcInstance pc, L1ItemInstance item) {
    Object[] petlist = pc.getPetList().values().toArray();
    Object[] array;
    int length = (array = petlist).length;
    int i = 0;
    while (i < length) {
      Object petObject = array[i];
      if (petObject instanceof L1PetInstance) {
        L1PetInstance pet = (L1PetInstance)petObject;
        if (item.getId() == pet.getItemObjId())
          return true; 
      } 
      i++;
    } 
    return false;
  }
  
  public byte[] getContent() {
    if (this._byte == null)
      this._byte = getBytes(); 
    return this._byte;
  }
  
  public String getType() {
    return getClass().getSimpleName();
  }
}
